package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.mapper.TokenMapper;
import com.example.mapper.UserMapper;
import com.example.pojo.Token;
import com.example.pojo.User;
import com.example.service.CodeService;
import com.example.service.UserService;
import com.example.utils.CookieUtil;
import com.example.utils.JwtUtil;
import com.example.utils.RSAUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Objects;

/**
 * @author lbq
 * @version 1.0
 * @date 2021/3/13 16:34
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    // @Autowired
    // private CodeFeign codeFeign;
    @Autowired
    private TokenMapper tokenMapper;
    @Autowired
    private UserMapper userMapper;
    @Reference(check = false)
    private CodeService codeService;

    /**
     * 注册接口
     *
     * @param email    邮箱地址
     * @param password 密码
     * @param code     验证码
     * @param response
     * @return
     */
    @Override
    public String register(String email, String password, String code, HttpServletResponse response) throws Exception {
        // String status = codeFeign.validate(email, code);
        String status = codeService.validate(email, code);
        if (Objects.equals("0", status)) {
            User user = new User().setEmail(email).setPassword(password).setRegisterTime(new Date());
            save(user);
            String token = null;
            try {
                token = JwtUtil.generateTokenExpireInMinutes(user, RSAUtil.getPrivateKey(RSAUtil.PRI_KEY_PATH), 60);
            } catch (Exception e) {
                e.printStackTrace();
            }
            tokenMapper.insert(new Token().setEmail(email).setToken(token));
            CookieUtil.newCookieBuilder()
                    .response(response)
                    .name("token")
                    .value(token)
                    .domain("localhost")
                    .httpOnly(true)
                    .build();
            return "0";
        }
        return "1";
    }

    /**
     * 根据邮箱地址判断是否已注册
     *
     * @param email 邮箱地址
     * @return
     */
    @Override
    public String isRegister(String email) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq(User.EMAIL, email);
        User user = userMapper.selectOne(wrapper);
        return user != null ? Boolean.FALSE.toString() : Boolean.TRUE.toString();
    }

    /**
     * 登录接口
     *
     * @param email    邮箱地址
     * @param password 密码
     * @param response
     * @return
     */
    @Override
    public String login(String email, String password, HttpServletResponse response) throws Exception {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq(User.EMAIL, email).eq(User.PASSWORD, password);
        User user = getOne(wrapper, false);
        if (user != null) {
            String token = JwtUtil.generateTokenExpireInMinutes(user, RSAUtil.getPrivateKey(RSAUtil.PRI_KEY_PATH), 60);
            Token one = tokenMapper.selectOne(new QueryWrapper<Token>().eq(Token.EMAIL, email));
            if (one == null) {
                tokenMapper.insert(new Token().setEmail(email).setToken(token));
            } else {
                tokenMapper.updateById(one.setToken(token));
            }
            CookieUtil.newCookieBuilder()
                    .response(response)
                    .name("token")
                    .value(token)
                    .domain("localhost")
                    .httpOnly(true)
                    .build();
            return Boolean.TRUE.toString();
        }
        return Boolean.FALSE.toString();
    }

    /**
     * 根据token查询用户登录邮箱
     *
     * @param token token
     * @return
     */
    @Override
    public String info(String token) {
        Token one = tokenMapper.selectOne(new QueryWrapper<Token>().eq(Token.TOKEN, token));
        return one.getEmail();
    }

}
